<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>      
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable style="width: 80px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" /> 
        </el-select>
      </el-form-item>      
      <el-form-item label="删除状态" prop="isDeleted">
        <el-select v-model="queryParams.isDeleted" placeholder="请选择删除状态" clearable style="width: 100px">
            <el-option label="未删除" :value="0" />
            <el-option label="已删除" :value="1" /> 
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="分类名称" align="center" prop="name" />
      <el-table-column label="父级分类" align="center" prop="parentId" />
      <el-table-column label="分类层级" align="center" prop="level">
        <template #default="scope">
          <span>
            <!-- 根据level数值显示对应的层级文字 -->
            {{ scope.row.level === 1 ? '一级分类' : 
               scope.row.level === 2 ? '二级分类' : 
               scope.row.level === 3 ? '三级分类' : 
               `超出层级` }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="图标" align="center" prop="icon" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{ scope.row.status === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作人" align="center" prop="operatorName" />
      <el-table-column label="逻辑删除" align="center" prop="isDeleted">
        <template #default="scope">
           <span>{{ scope.row.isDeleted === 1 ? '已删除' : '未删除' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:category:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-select 
            v-model="form.parentId" 
            placeholder="请选择父级分类"
            clearable
          >
            <el-option label="顶级分类" :value="0" />
            <el-option 
              v-for="category in allCategories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id"
              :disabled="category.id === form.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类层级" prop="level">
          <el-select v-model="form.level" placeholder="请选择分类层级">
            <el-option label="一级分类" :value="1" />
            <el-option label="二级分类" :value="2" />
            <el-option label="三级分类" :value="3" />
            <!-- 可根据需要添加更多层级 -->
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序序号，数值越小越靠前" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/system/category"
import useUserStore from '@/store/modules/user'
const userStore = useUserStore();

const { proxy } = getCurrentInstance()

const categoryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const allCategories = ref([])

const data = reactive({
  form: {
    operatorName: userStore.nickName // 添加操作人名称
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    parentId: null,
    level: null,
    sortOrder: null,
    icon: null,
    status:1,
    description: null,
    operatorName: null,
    isDeleted: 0,
  },
  rules: {
    name: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "分类层级，1=一级分类，2=二级分类，以此类推不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "分类状态：0=禁用，1=启用不能为空", trigger: "change" }
    ],
    operatorName: [
      { required: true, message: "操作人昵称，记录最后操作该分类的用户昵称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品分类列表 */
function getList() {
  loading.value = true
  listCategory(queryParams.value).then(response => {
    //console.log('接口返回数据:', response.rows); // 检查这里是否只有一条新数据
    categoryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}


/** 获取所有分类（用于父级分类选择） */
function getAllCategories() {
  // 这里需要获取所有未删除的分类，所以参数要设置isDeleted: 0
  const params = {
    pageNum: 1,
    pageSize: 1000, // 假设最多1000个分类，足够使用
    isDeleted: 0
  }
  listCategory(params).then(response => {
    allCategories.value = response.rows
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    parentId: null,
    level: 1,
    sortOrder: null,
    icon: null,
    status: 1,
    description: null,
    operatorName: null,
    isDeleted: 0,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("categoryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品分类"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value[0]
  getCategory(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品分类"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      form.value.operatorName = userStore.nickName;
      if (form.value.id != null) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品分类编号为"' + _ids + '"的数据项？').then(function() {
    return delCategory(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/category/export', {
    ...queryParams.value
  }, `category_${new Date().getTime()}.xlsx`)
}

defineExpose({
  allCategories
})
getList()
getAllCategories() //加载所有分类数据
</script>
